package com.ac.scum.log.web.model.player.service;

import com.ac.common.core.exception.BaseException;
import com.ac.common.core.exception.config.ExceptionType;
import com.ac.scum.log.web.model.player.mapper.PlayerRechargeTradeMapper;
import com.ac.scum.log.web.utils.user.CurrentUserUtil;
import com.ac.scum.player.bean.PlayerBalance;
import com.ac.scum.player.bean.PlayerRechargeTrade;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Slf4j
@Service
@AllArgsConstructor
public class PlayerRechargeTradeService extends ServiceImpl<PlayerRechargeTradeMapper, PlayerRechargeTrade> {

    private final PlayerBalanceService playerBalanceService;

    /**
     * 玩家充值
     */
    @Transactional
    public Boolean recharge(PlayerRechargeTrade playerRechargeTrade) throws BaseException {
        if (playerRechargeTrade == null) {
            throw new BaseException(ExceptionType.Parameter_Error.of("入参错误"));
        }
        if (playerRechargeTrade.getAmount() == null) {
            throw new BaseException(ExceptionType.Parameter_Error.of("充值金额不能为空"));
        }
        if (playerRechargeTrade.getPlayerId() == null) {
            throw new BaseException(ExceptionType.Parameter_Error.of("玩家id不能为空"));
        }
        playerRechargeTrade.setServerId(CurrentUserUtil.getCurrentServerId());
        this.save(playerRechargeTrade);

        PlayerBalance playerBalance = playerBalanceService.findPlayerBalance(playerRechargeTrade.getServerId(), playerRechargeTrade.getPlayerId());
        playerBalance.setBalance(playerBalance.getBalance() + playerRechargeTrade.getAmount());
        playerBalance.setTotalBalance(playerBalance.getTotalBalance() + playerRechargeTrade.getAmount());
        playerBalance.setLastRechargeTradeId(playerRechargeTrade.getId());
        playerBalance.setLastRechargeTime(LocalDateTime.now());
        playerBalanceService.updateById(playerBalance);

        return Boolean.TRUE;
    }
}
